import os
import time

from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
import json
import xlrd

# Create your views here.
from backend import settings


class UserViews:
    @staticmethod
    # 用户登录
    def userLogin(request):
        data = json.loads(request.body)
        response = {'code': 0, 'msg': 'success'}

        username = data.get("username")
        password = data.get("password")

        if username and password:
            # 身份认证信息
            loginUser = authenticate(request, username=username, password=password)
            if loginUser:
                # 将认证信息绑定到当前request中
                login(request, loginUser)
                response['username'] = loginUser.username
                return JsonResponse(response)
            else:
                response['code'] = -1
                response['msg'] = "认证失败,请检查账号密码是否正确"
                return JsonResponse(response)
        else:
            response['code'] = -1
            response['msg'] = "用户名或密码不能为空"
            return JsonResponse(response)

    @staticmethod
    # 用户注销
    def userLogout(request):
        data = json.loads(request.body)
        response = {'code': 0, 'msg': 'success'}

        if request.user.is_authenticated:
            logout(request)
            return JsonResponse(response)
        else:
            response['code'] = -1
            response['msg'] = "当前未登录"
            return JsonResponse(response)

    @staticmethod
    # 用户注册
    def userRegister(request):
        data = json.loads(request.body)
        response = {'code': 0, 'msg': 'success'}

        username = data.get('username')
        password = data.get('password')
        email = data.get('email')

        user = User.objects.filter(username=username).first()
        if username and password and email:
            if user is None:
                user = User.objects.create_user(username=username, password=password, email=email)
                user.save()
                response['userInfo'] = {'username': username, 'id': user.pk}
                return JsonResponse(response)
            else:
                response['code'] = -1
                response['msg'] = "用户名已存在"
                return JsonResponse(response)
        else:
            response['code'] = -1
            response['msg'] = "用户名/密码/邮箱不能为空"
            return JsonResponse(response)

    @staticmethod
    # 用户更改信息,需要登陆
    def userChangeInfo(request):
        data = json.loads(request.body)
        response = {'code': 0, 'msg': 'success'}

        username = data.get('username')
        password = data.get('password')
        email = data.get('email')

        if username:
            try:
                nowUser = User.objects.get(username=username)
                if password:
                    nowUser.set_password(password)
                if email:
                    nowUser.email = email
                nowUser.save()
                return JsonResponse(response)
            except:
                response['code'] = -1
                response['msg'] = "用户不存在或未登录"
                return JsonResponse(response)
        else:
            response['code'] = -1
            response['msg'] = "请传入username"
            return JsonResponse(response)

    @staticmethod
    def userResetPassword(request):
        data = json.loads(request.body)
        response = {'code': 0, 'msg': 'success'}

        username = data.get('username')
        email = data.get('email')
        newpassword = data.get('newpassword')

        user = User.objects.get(username=username)
        if user:
            if user.email == email:
                user.set_password(newpassword)
                user.save()
                return JsonResponse(response)
            else:
                response['code'] = -1
                response['msg'] = "用户名与邮箱不匹配"
                return JsonResponse(response)
        else:
            response['code'] = -1
            response['msg'] = "用户不存在"
            return JsonResponse(response)

    @staticmethod
    # 用户获取信息
    def userGetInfo(request):
        data = json.loads(request.body)
        response = {'code': 0, 'msg': 'success'}

        username = data.get('username')

        if username:
            try:
                user = User.objects.get(username=username)
                response['userinfo'] = {'username': user.username, 'email': user.email, }
                return JsonResponse(response)
            except:
                response['code'] = -1
                response['msg'] = "用户不存在"
                return JsonResponse(response)
        else:
            response['code'] = -1
            response['msg'] = "请传入username"
            return JsonResponse(response)

    @staticmethod
    # 从Excel批量导入用户
    def importUser(request):
        response = {'code': 0, 'msg': 'success'}
        # 根name取 file 的值
        file = request.FILES.get('file')
        # 创建upload文件夹
        if not os.path.exists(settings.UPLOAD_ROOT):
            os.makedirs(settings.UPLOAD_ROOT)
        try:
            if file is None:
                response['code'] = -1
                response['msg'] = '获取文件失败'
                return JsonResponse(response)
            # 循环二进制写入
            filename = 'upload_' + time.strftime("%Y%m%d%H%M%S", time.localtime()) + '.xls'
            with open(settings.UPLOAD_ROOT + "/" + filename, 'wb') as xls:
                for i in file.readlines():
                    xls.write(i)
        except:
            response['code'] = -1
            response['msg'] = '系统错误'
            return JsonResponse(response)
        # return JsonResponse(response)
        wb = xlrd.open_workbook(settings.UPLOAD_ROOT + "/" + filename)
        sheet = wb.sheet_by_name('Sheet1')
        failList = []
        successList = []
        for a in range(sheet.nrows):
            username = str(int(sheet.cell_value(a, 0)) if (
                    sheet.cell(a, 0).ctype == 2 and sheet.cell_value(a, 0) % 1 == 0.0) else sheet.cell_value(a, 0))
            password = str(int(sheet.cell_value(a, 1)) if (
                    sheet.cell(a, 1).ctype == 2 and sheet.cell_value(a, 1) % 1 == 0.0) else sheet.cell_value(a, 1))
            # print(username+' '+password)
            # email = username+'@admin.com'
            try:
                user = User.objects.create_user(username=username, password=password)
                user.save()
                successList.append({'username': username, 'password': password})
            except:
                failList.append({'username': username, 'password': password})
        response['failed'] = failList
        return JsonResponse(response)
